/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-08-09 14:23:43
 */
import { Button, Card, Divider, Form, Input, Modal, Table, Upload, message, } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import React, { useEffect, useState } from 'react'
import { ColumnsType } from 'antd/lib/table';
import { reqAddBaseTrademarkRes, reqRemoveRes, reqTrademarkRes, reqUpdateBaseTrademark } from '@/api/prodect/trademark';
import { reqTrademarkRecord } from '@/api/prodect/trademarkType';
import { UploadProps } from 'antd/lib/upload';

export default function Trademark() {

  const [messageApi, contextHolder] = message.useMessage();

  //#region 表格渲染逻辑
    // 表格加载
    let [loading,setLoading]=useState<boolean>(false)

    // 声明当前页面状态
    let [current,setCurrent]=useState<number>(1)
    // 声明页面显示条数状态
    let [pageSize,setPageSize]=useState<number>(5)
    // 声明所有数据状态
    let [total,setTotal]=useState<number>(0)

    let [trademark,setTrademark]=useState<reqTrademarkRecord[]>([])
  // 获取表格列表
  let getTrademark=async ()=>{
    setLoading(true)
    let res=await reqTrademarkRes(current,pageSize)
    // console.log(res.data);-----------------------------------------------
    setTotal(res.data.total)
    setTrademark(res.data.records)
    setLoading(false)

  }

  // 初始化获取数据
  useEffect(()=>{
    getTrademark()
  },[current,pageSize])

  
  const columns:ColumnsType<any> = [
    {
      title: '序号',
      width: 100,
      align: "center",
      render: (value: any, record: any, index: number) => {
        return index + 1
      }
    },
    {
      title: '品牌名称',
      dataIndex: 'tmName',
      align:'center'
      
    },
    {
      title: '品牌LOGO',
      dataIndex: 'logoUrl',
      width:400,
      align:'center',
      render:(key)=>{
        return <img style={{width:80}} src={key} alt="" />
      }
    },
    {
      title: '操作',
      align:'center',
      width:300,
      render:(row:reqTrademarkRecord)=>{
        return <>
          <Button type="primary" onClick={editTrademark(row)}>修改</Button>
          <Button className='ml' type="primary" danger onClick={detailTrademark(row)}>删除</Button>
        </>
      }

    },
  ];

  const detailTrademark=(row:reqTrademarkRecord)=>{
    return async ()=>{
      await reqRemoveRes(Number(row.id))
    getTrademark()

    }
  }

  let changePage=(page=current,limit=pageSize)=>{
    
    setCurrent(page)
    setPageSize(limit)
  }
//#endregion

//#region 弹出框逻辑
  // 对添加修改框的控制

  let [isModalOpen, setIsModalOpen] = useState(false);

// 点击添加按钮弹出输入框
  const showModal = () => {
    setIsModalOpen(true);
  };

  const [form] = Form.useForm();

// 修改按钮
const editTrademark=(row:reqTrademarkRecord)=>{
  return  ()=>{
    form.setFieldsValue({
      "name":row.tmName,
      "url":'+'
    })
    setImageUrl(row.logoUrl)
    setId(row.id)
    setIsModalOpen(true);
  }
  
}

// 点击确定  
const onFinish =async (values: any) => {
  const res=id?await reqUpdateBaseTrademark({
    id, tmName:values.name, logoUrl:imageUrl  as string
  }):
  await reqAddBaseTrademarkRes({ logoUrl: imageUrl as string, tmName: values.name })

  
  if(res.code===200){
    if(id){
      messageApi.open({
        type: 'success',
        content: '修改成功',
      });
    }else{
      messageApi.open({
        type: 'success',
        content: '添加成功',
      });
    }
    
    form.resetFields();
    setImageUrl('')
    setIsModalOpen(false);
    getTrademark()
  }
  
};
// 点击取消
const onReset = () => {
  form.resetFields();
  setImageUrl('')
  setIsModalOpen(false);

};
const [id,setId]=useState<string>()
// 添加的图片
const [imageUrl, setImageUrl] = useState<string>();
const onChange: UploadProps['onChange'] = (file) => {
  
  if(file.file.response){
    setImageUrl(file.file.response.data)
  }
};


// 品牌名称类型
  type FieldType = {
    name?: string;
    url?:any
  };

//#endregion
  return (
    <Card>
      {contextHolder}
      <Button type="primary" onClick={showModal}  icon={<PlusOutlined rev={undefined}/>}>
        添加
      </Button>
      <Modal title={id?'修改属性':'添加属性'} centered open={isModalOpen}  footer={null} onCancel={onReset}>

        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
        <Form.Item<FieldType>
          label="Name"
          name="name"
          rules={[{ required: true, message: '请填写品牌名称' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item<FieldType> 
        name="url" 
        label="图片" 
        rules={[{ required: true }]}
        >

        <Upload
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          action="/api/admin/product/upload"
          onChange={onChange}
        >
          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : '+'}
        </Upload>

        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
        <Button type="primary" onClick={onReset}>
            取消
          </Button>
          <Button className='ml' type="primary" htmlType="submit">
            确定
          </Button>
        </Form.Item>
        </Form>
      </Modal>

      {/* 表格 */}
      <Divider />
      <Table size="small"
        rowKey={'id'} 
        bordered 
        dataSource={trademark} 
        columns={columns} 
        loading={loading}
      // 分页功能
        pagination={
          {
            current,
            total,
            pageSize,
            pageSizeOptions: [5],
            showSizeChanger: true,
            showQuickJumper: true,
            onChange:changePage,
            showTotal: (total: number) => {
              return <span>总共：{total} 条</span>
            }

          }
        } />
    </Card>
  )
}
